import React from 'react';
import clsx from 'clsx';
import { SpaceProps } from './PropsType';
import useNamespace from '../utils/useNamespace';

const formatGap = (gap: string | number) => (typeof gap === 'number' ? `${gap}px` : gap);

const Space: React.FC<SpaceProps> = ({
  wrap,
  block,
  direction = 'horizontal',
  align,
  justify,
  gap,
  style,
  className,
  onClick,
  children,
}) => {
  const [bem] = useNamespace('space');

  const computedStyle = React.useMemo(() => {
    if (gap) {
      if (Array.isArray(gap)) {
        const [gapH, gapV] = gap;
        return {
          ...style,
          '--gap-vertical': formatGap(gapV ?? 0),
          '--gap-horizontal': formatGap(gapH ?? 0),
        } as React.CSSProperties;
      }
      return { ...style, '--gap': formatGap(gap as string | number) } as React.CSSProperties;
    }
    return style;
  }, [gap, style]);

  return (
    <div
      className={clsx(
        className,
        bem({
          wrap,
          block,
          [`${direction}`]: !!direction,
          [`align-${align}`]: !!align,
          [`justify-${justify}`]: !!justify,
        }),
      )}
      style={computedStyle}
      onClick={onClick}
    >
      {React.Children.map(children, (child) => {
        return (
          child !== null && child !== undefined && <div className={clsx(bem('item'))}>{child}</div>
        );
      })}
    </div>
  );
};

export default Space;
